package org.raymond.iworks.study.flowable.chatgpt;

import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.impl.cfg.StandaloneProcessEngineConfiguration;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
public class FlowableRollbackExample {
    public static void main(String[] args) {
        // 创建流程引擎
        ProcessEngineConfiguration cfg = new StandaloneProcessEngineConfiguration()
                .setJdbcUrl("jdbc:h2:mem:flowable;DB_CLOSE_DELAY=-1")
                .setJdbcUsername("sa")
                .setJdbcPassword("")
                .setJdbcDriver("org.h2.Driver")
                // 设置为true才能触发计时器Timer事件
                .setAsyncExecutorActivate(true)
                .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
        ProcessEngine processEngine = cfg.buildProcessEngine();

        // 部署流程定义
        Deployment deployment = processEngine.getRepositoryService().createDeployment()
                .addClasspathResource("flowable/rollbackProcess.bpmn20.xml") // 流程定义文件
                .deploy();

        // 启动流程实例
        RuntimeService runtimeService = processEngine.getRuntimeService();
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("rollbackProcess");

        // 处理第一个任务
        TaskService taskService = processEngine.getTaskService();
        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        System.out.println("当前任务: " + task.getName());

        // 完成第一个任务
        taskService.complete(task.getId());

        // 处理回退任务
        task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        System.out.println("当前任务: " + task.getName());

        // 回退到上一个节点
        /*
        runtimeService.createChangeActivityStateBuilder()
                .processInstanceId(processInstance.getId())
                .moveActivityIdTo("rollbackTask", "userTask")
                .changeState();
         */

        // 处理回退后的任务
        task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        System.out.println("当前任务: " + task.getName());

        // 完成回退后的任务
        taskService.complete(task.getId());
        System.out.println("当前任务: " + task.getName());

        // 验证流程是否已经结束
        long count = runtimeService.createProcessInstanceQuery().processInstanceId(processInstance.getId()).count();
        if (count == 0) {
            System.out.println("流程已结束");
        } else {
            System.out.println("流程未结束");
        }

        // 关闭流程引擎
        processEngine.close();
        processEngine = null;
    }
}
